package fr.machizaud.research.handlers;

import fr.machizaud.research.MalformedDocumentException;
import fr.machizaud.research.XMLHandler;
import org.jdom.Document;
import org.jdom.Element;

import java.util.logging.Level;

/**
 * User: Andréa
 * Date: 23/01/11
 * Time: 16:39
 * <p/>
 * Remove all unused markup
 */
public class UnusedMarkupCleaner
        implements XMLHandler {
    private static final java.util.logging.Logger logger =
            java.util.logging.Logger.getLogger(UnusedMarkupCleaner.class.getCanonicalName());

    private static final String ATL_TRANSFORMATION_ROOT = "DocumentRoot";

    private UnusedMarkupCleaner() {
    }

    private static class UnusedMarkupCleanerHolder {
        private static final UnusedMarkupCleaner instance = new UnusedMarkupCleaner();
    }

    public static UnusedMarkupCleaner getInstance() {
        return UnusedMarkupCleanerHolder.instance;
    }

    @Override
    public void process(Document dom) throws MalformedDocumentException {
        logger.log(Level.INFO, "Handler {0}", getClass().getName());
        Element root = dom.getRootElement();
        logger.log(Level.FINE, "Getting root node : {0}", root);

        //clean unused fcp:DocumentRoot
        if (root.getName().equals(ATL_TRANSFORMATION_ROOT)) {
            //set the proper FCP XML Interchange root node
            Element xmeml = root.getChild("xmeml");
            logger.log(Level.FINE, "Getting 'xmeml' child : {0}", xmeml);
            if (xmeml == null)
                throw new MalformedDocumentException(
                        "Given document doesn't have a 'xmeml' node properly set",
                        getClass());
            else
                dom.setRootElement((Element)xmeml.detach());
        } else {
                throw new MalformedDocumentException(
                        "Given document doesn't have a 'DocumentRoot' root node",
                        getClass());
        }

        logger.log(Level.FINER, "Handler {0} : resulting dom {1}",
                new Object[]{
                        getClass(), dom
                }
        );
    }
}
